package com.ssplayer.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.ssplayer.application.MyApplication;
import com.ssplayer.bean.Music;
import com.ssplayer.bean.MusicAction;
import com.ssplayer.bean.MusicMsg;
import com.ssplayer.custom.LrcView;
import com.ssplayer.utils.MediaUtils;

@SuppressLint("NewApi")
public class MusicPlayerActivity extends Activity implements OnClickListener {

	private MyApplication myApp;
	private SharedPreferences sharedPreferences;
	private TextView music_player_title, music_player_artist,
			music_player_mode_display, music_current, music_duration;
	private LinearLayout button_back, music_player_mode;
	private ImageView button_play, button_pause, button_stop, button_previous,
			button_next, button_volume;
	private SeekBar music_seekBar, volume_seekBar;
	private MusicPlayerReceiver mpReceiver;
	private List<Music> musics;
	private int currentTime = 0;// 当前播放的时间
	private int currentMusic = 0;// 当前播放的音乐位置

	private AudioManager audioManager;
	private Timer timer;
	private int maxVolume;
	private int currentVolume;
	public static LrcView lrcView;

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MusicMsg.HIDE_MSG:
				volume_seekBar.setVisibility(View.GONE);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_music_player);
		myApp = (MyApplication) getApplication();
		sharedPreferences = getSharedPreferences("musicStore",
				Context.MODE_PRIVATE);
		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		musics = MediaUtils.getMusics(getApplicationContext(),myApp.getCurrentlist());
		// 得到音乐播放界面所有控件
		findAllViews();
		Intent intent = getIntent();
		// 根据获取的Intent初始化界面
		initMusic(intent);
		registerMusicPlayRecevier();
		initLyric();
	}

	private void findAllViews() {
		// 标题
		music_player_title = (TextView) findViewById(R.id.music_player_title);
		music_player_artist = (TextView) findViewById(R.id.music_player_artist);
		// 控制按钮
		button_back = (LinearLayout) findViewById(R.id.button_back);
		music_player_mode = (LinearLayout) findViewById(R.id.music_player_mode);
		music_player_mode_display = (TextView) findViewById(R.id.music_player_mode_display);
		button_play = (ImageView) findViewById(R.id.button_play);
		button_pause = (ImageView) findViewById(R.id.button_pause);
		button_stop = (ImageView) findViewById(R.id.button_stop);
		button_previous = (ImageView) findViewById(R.id.button_previous);
		button_next = (ImageView) findViewById(R.id.button_next);
		button_volume = (ImageView) findViewById(R.id.button_volume);
		// 歌词显示
		lrcView = (LrcView) findViewById(R.id.lyricshow);
		// 进度条
		music_current = (TextView) findViewById(R.id.music_current);
		music_duration = (TextView) findViewById(R.id.music_duration);
		music_seekBar = (SeekBar) findViewById(R.id.music_seekbar);
		volume_seekBar = (SeekBar) findViewById(R.id.volume_seekBar);
		// 添加监听事件
		button_back.setOnClickListener(this);
		music_player_mode.setOnClickListener(this);
		button_play.setOnClickListener(this);
		button_pause.setOnClickListener(this);
		button_stop.setOnClickListener(this);
		button_previous.setOnClickListener(this);
		button_next.setOnClickListener(this);
		button_volume.setOnClickListener(this);
		music_seekBar.setOnSeekBarChangeListener(new MusicSeekBarListener());
		volume_seekBar.setOnSeekBarChangeListener(new MusicSeekBarListener());
	}

	/**
	 * 显示当前播放的音乐及相关信息
	 */
	@SuppressLint("UseValueOf")
	private void initMusic(Intent intent) {
		currentMusic = intent.getIntExtra("currentMusic", 0);
		currentTime = intent.getIntExtra("currentTime", 0);
		getPlayStatus();
		// 设置播放模式
		switch (getPlayMode()) {
		case MusicMsg.MODE_ORDER:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_order));
			break;
		case MusicMsg.MODE_SHUFFLE:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_shuffle));
			break;
		case MusicMsg.MODE_REPEAT_ONCE:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_repeat_once));

			break;
		}
		music_player_title.setText(musics.get(currentMusic).getTitle());
		music_player_artist.setText(musics.get(currentMusic).getArtist());
		// 初始化进度条
		music_seekBar.setMax(new Long(musics.get(currentMusic).getDuration())
				.intValue());
		music_seekBar.setProgress(currentTime);
		music_duration.setText(String.valueOf(MediaUtils
				.formatDuration(currentTime)));
		music_duration.setText(String.valueOf(MediaUtils.formatDuration(musics
				.get(currentMusic).getDuration())));
		// 获取音量信息,初始化音量进度条
		maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		volume_seekBar.setMax(maxVolume);
		setMusicVolume(currentVolume);
	}

	/**
	 * 启动服务显示歌词
	 */
	public void initLyric() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("currentMusic", currentMusic);
		intent.putExtra("msg", MusicMsg.SHOWLRC_MSG);
		startService(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_back:
			finish();
			break;
		case R.id.music_player_mode:
			changeMode();
			break;
		case R.id.button_play:// 播放
			play();
			break;
		case R.id.button_pause:// 暂停
			pause();
			break;
		case R.id.button_previous:// 上一首
			pervious();
			break;
		case R.id.button_next:// 下一首
			next();
			break;
		case R.id.button_stop:// 停止播放
			stop();
			break;
		case R.id.button_volume:// 显示隐藏音量面板
			changeVolumePanel();
			break;
		}
	}

	private void changeMode() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		switch (getPlayMode()) {
		// 如果为顺序播放，单击进入随机播放
		case MusicMsg.MODE_ORDER:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_shuffle));
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.mode_shuffle_string),
					Toast.LENGTH_SHORT).show();
			// myApp.setMplay_mode(MusicMsg.MODE_SHUFFLE);
			savePlayMode(sharedPreferences, MusicMsg.MODE_SHUFFLE);
			break;

		// 如果为随机播放，单击进入单曲循环
		case MusicMsg.MODE_SHUFFLE:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_repeat_once));
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.mode_repeat_once_string),
					Toast.LENGTH_SHORT).show();
			// myApp.setMplay_mode(MusicMsg.MODE_REPEAT_ONCE);
			savePlayMode(sharedPreferences, MusicMsg.MODE_REPEAT_ONCE);
			break;

		// 如果为单曲循环，单击进入顺序播放
		case MusicMsg.MODE_REPEAT_ONCE:
			music_player_mode_display.setBackground(getResources().getDrawable(
					R.drawable.mode_order));
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.mode_order_string),
					Toast.LENGTH_SHORT).show();
			// myApp.setMplay_mode(MusicMsg.MODE_ORDER);
			savePlayMode(sharedPreferences, MusicMsg.MODE_ORDER);
			break;

		default:
			break;
		}
	}

	/**
	 * 保存播放模式
	 * 
	 * @param sharedPreferences
	 * @param modeShuffle
	 */
	private void savePlayMode(SharedPreferences sharedPreferences, int playMode) {
		Editor editor = sharedPreferences.edit();
		editor.putInt("play_mode", playMode);
		editor.commit();
	}

	private int getPlayMode() {
		// TODO Auto-generated method stub
		return sharedPreferences.getInt("play_mode", MusicMsg.MODE_ORDER);
	}

	/**
	 * 播放
	 */
	private void play() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("currentMusic", currentMusic);
		switch (myApp.getMplay_status()) {
		// 如果播放状态为暂停，继续播放
		case MusicMsg.STATUS_PAUSE:
			intent.putExtra("msg", MusicMsg.CONTINUE_MSG);
			break;
		// 如果播放状态为停止，重新播放
		case MusicMsg.STATUS_STOP:
			intent.putExtra("msg", MusicMsg.PLAY_MSG);
			break;
		default:
			break;
		}
		startService(intent);

	}

	/**
	 * 暂停
	 */
	private void pause() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("msg", MusicMsg.PAUSE_MSG);
		intent.putExtra("currentMusic", currentMusic);
		startService(intent);
	}

	/**
	 * 上一首
	 */
	private void pervious() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("msg", MusicMsg.PREVIOUS_MSG);
		intent.putExtra("currentMusic", currentMusic);
		startService(intent);

	}

	/**
	 * 下一首
	 */
	private void next() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("msg", MusicMsg.NEXT_MSG);
		intent.putExtra("currentMusic", currentMusic);
		startService(intent);

	}

	/**
	 * 停止播放
	 */
	private void stop() {
		Intent intent = new Intent();
		intent.setAction(MusicAction.MUSIC_SERVICE);
		intent.putExtra("msg", MusicMsg.STOP_MSG);
		intent.putExtra("currentMusic", currentMusic);
		startService(intent);

	}

	private void changeVolumePanel() {
		int status = volume_seekBar.getVisibility();
		switch (status) {
		case View.VISIBLE:
			volume_seekBar.setVisibility(View.GONE);
			timer.cancel();
			break;
		case View.GONE:
			showThenHideVolume();
			break;
		default:
			break;
		}
	}

	/**
	 * 显示音量面板，三秒后自动关闭
	 */
	private void showThenHideVolume() {
		// 如果音量面板已经可见，则取消定时器
		if (volume_seekBar.getVisibility() == View.VISIBLE) {
			timer.cancel();
		}
		volume_seekBar.setVisibility(View.VISIBLE);
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(MusicMsg.HIDE_MSG);
				timer.cancel();
			}

		}, 3000);

	}

	/**
	 * 判断是否有音乐在播放，设置暂停或播放键
	 * 
	 */
	private void getPlayStatus() {
		switch (myApp.getMplay_status()) {
		case MusicMsg.STATUS_PLAYING:
			button_play.setVisibility(View.GONE);
			button_pause.setVisibility(View.VISIBLE);
			break;

		default:
			button_play.setVisibility(View.VISIBLE);
			button_pause.setVisibility(View.GONE);
			break;
		}
	}

	/**
	 * 注册广播
	 */
	private void registerMusicPlayRecevier() {
		mpReceiver = new MusicPlayerReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicAction.UPDATE_ACTION);
		filter.addAction(MusicAction.MUSIC_CURRENT);
		filter.addAction(MusicAction.CONTROL_ACTION);
		registerReceiver(mpReceiver, filter);

	}

	public class MusicPlayerReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			switch (action) {
			case MusicAction.UPDATE_ACTION:
				initMusic(intent);
				break;
			case MusicAction.MUSIC_CURRENT:
				currentTime = intent.getIntExtra("currentTime", 0);
				music_seekBar.setProgress(currentTime);
				music_current.setText(String.valueOf(MediaUtils
						.formatDuration(currentTime)));
				break;
			case MusicAction.CONTROL_ACTION:
				getPlayStatus();
				break;
			default:
				break;
			}
		}

	}

	public class MusicSeekBarListener implements OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			switch (seekBar.getId()) {

			case R.id.volume_seekBar:
				if (fromUser) {
					currentVolume = progress;
					setMusicVolume(progress);
				}
				break;
			}

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {

			switch (seekBar.getId()) {
			case R.id.volume_seekBar:
				//调节音量时取消定时器
				timer.cancel();
				break;
			case R.id.music_seekbar:
				// 开始拖动进度条反注册广播，防止进度条因为音乐进度改变跳动
				unregisterReceiver(mpReceiver);
				break;
			}
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {

			switch (seekBar.getId()) {
			case R.id.music_seekbar:
				registerMusicPlayRecevier();
				Intent intent = new Intent();
				intent.setAction(MusicAction.MUSIC_SERVICE);
				intent.putExtra("currentMusic", currentMusic);
				intent.putExtra("currentTime", seekBar.getProgress());
				intent.putExtra("msg", MusicMsg.PROGRESS_CHANGE);
				startService(intent);
				break;

			case R.id.volume_seekBar:

				showThenHideVolume();
				break;
			}
		}

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int action = event.getAction();
		int keycode = event.getKeyCode();
		switch (keycode) {
		case KeyEvent.KEYCODE_VOLUME_UP:// 按音量加键
			if (action == KeyEvent.ACTION_DOWN) {
				showThenHideVolume();
				if (currentVolume < maxVolume) {
					currentVolume++;
				}
				setMusicVolume(currentVolume);
				// 隐藏系统进度条
				return true;
			}
			break;
		case KeyEvent.KEYCODE_VOLUME_DOWN:// 按音量加键
			if (action == KeyEvent.ACTION_DOWN) {
				showThenHideVolume();
				if (currentVolume > 0) {
					currentVolume--;
				}
				setMusicVolume(currentVolume);
				// 隐藏系统进度条
				return true;
			}
			break;
		}

		return super.dispatchKeyEvent(event);
	}

	/**
	 * 设置音量
	 * 
	 * @param currentVolume
	 */
	private void setMusicVolume(int currentVolume) {
		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume,
				AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
		volume_seekBar.setProgress(currentVolume);
		// 音量按钮随音量改变
		int volumeValue;
		if (currentVolume > 0) {
			volumeValue = currentVolume / (maxVolume / 3);
			switch (volumeValue) {
			case 0:
				button_volume.setBackground(getResources().getDrawable(
						R.drawable.button_volume1));
				break;
			case 1:
				button_volume.setBackground(getResources().getDrawable(
						R.drawable.button_volume2));
				break;
			default:
				button_volume.setBackground(getResources().getDrawable(
						R.drawable.button_volume3));
				break;
			}
		} else {
			button_volume.setBackground(getResources().getDrawable(
					R.drawable.button_volume0));
		}

	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mpReceiver);
		super.onDestroy();
	}

}
